"""
数据库配置管理模块
支持多种数据库类型的配置和连接管理
"""

import os
from typing import Dict, Any, Optional
from dataclasses import dataclass
from enum import Enum


class DatabaseType(Enum):
    """支持的数据库类型"""
    MYSQL = "mysql"
    POSTGRESQL = "postgresql"
    ORACLE = "oracle"
    SQLSERVER = "sqlserver"
    SQLITE = "sqlite"


@dataclass
class DatabaseConfig:
    """数据库连接配置"""
    db_type: DatabaseType
    host: str
    port: int
    database: str
    username: str
    password: str
    charset: str = "utf8mb4"
    ssl_mode: Optional[str] = None
    connection_timeout: int = 30
    pool_size: int = 10
    max_overflow: int = 20
    pool_timeout: int = 30
    pool_recycle: int = 3600
    echo: bool = False


class DatabaseConfigManager:
    """数据库配置管理器"""
    
    def __init__(self):
        self.configs: Dict[str, DatabaseConfig] = {}
        self.default_configs = self._load_default_configs()
    
    def _load_default_configs(self) -> Dict[str, Dict[str, Any]]:
        """加载默认配置"""
        return {
            DatabaseType.MYSQL.value: {
                "port": 3306,
                "charset": "utf8mb4",
                "driver": "pymysql"
            },
            DatabaseType.POSTGRESQL.value: {
                "port": 5432,
                "charset": "utf8",
                "driver": "psycopg2"
            },
            DatabaseType.ORACLE.value: {
                "port": 1521,
                "charset": "utf8",
                "driver": "cx_oracle"
            },
            DatabaseType.SQLSERVER.value: {
                "port": 1433,
                "charset": "utf8",
                "driver": "pyodbc"
            },
            DatabaseType.SQLITE.value: {
                "port": None,
                "charset": "utf8",
                "driver": "sqlite3"
            }
        }
    
    def add_config(self, name: str, config: DatabaseConfig) -> None:
        """添加数据库配置"""
        self.configs[name] = config
    
    def get_config(self, name: str) -> Optional[DatabaseConfig]:
        """获取数据库配置"""
        return self.configs.get(name)
    
    def remove_config(self, name: str) -> bool:
        """删除数据库配置"""
        if name in self.configs:
            del self.configs[name]
            return True
        return False
    
    def list_configs(self) -> Dict[str, DatabaseConfig]:
        """获取所有配置"""
        return self.configs.copy()
    
    def get_connection_string(self, name: str) -> Optional[str]:
        """获取数据库连接字符串"""
        config = self.get_config(name)
        if not config:
            return None
        
        defaults = self.default_configs.get(config.db_type.value, {})
        driver = defaults.get("driver", "")
        
        if config.db_type == DatabaseType.MYSQL:
            return f"mysql+{driver}://{config.username}:{config.password}@{config.host}:{config.port}/{config.database}?charset={config.charset}"
        
        elif config.db_type == DatabaseType.POSTGRESQL:
            return f"postgresql+{driver}://{config.username}:{config.password}@{config.host}:{config.port}/{config.database}"
        
        elif config.db_type == DatabaseType.ORACLE:
            return f"oracle+{driver}://{config.username}:{config.password}@{config.host}:{config.port}/{config.database}"
        
        elif config.db_type == DatabaseType.SQLSERVER:
            return f"mssql+{driver}://{config.username}:{config.password}@{config.host}:{config.port}/{config.database}?driver=ODBC+Driver+17+for+SQL+Server"
        
        elif config.db_type == DatabaseType.SQLITE:
            return f"sqlite:///{config.database}"
        
        return None
    
    def validate_config(self, config: DatabaseConfig) -> bool:
        """验证配置有效性"""
        if not config.host and config.db_type != DatabaseType.SQLITE:
            return False
        if not config.database:
            return False
        if not config.username and config.db_type != DatabaseType.SQLITE:
            return False
        return True


# 全局配置管理器实例
db_config_manager = DatabaseConfigManager()


# 环境变量配置加载
def load_config_from_env() -> None:
    """从环境变量加载数据库配置"""
    
    # MySQL配置
    if all([os.getenv('MYSQL_HOST'), os.getenv('MYSQL_DATABASE'), 
            os.getenv('MYSQL_USERNAME'), os.getenv('MYSQL_PASSWORD')]):
        mysql_config = DatabaseConfig(
            db_type=DatabaseType.MYSQL,
            host=os.getenv('MYSQL_HOST'),
            port=int(os.getenv('MYSQL_PORT', 3306)),
            database=os.getenv('MYSQL_DATABASE'),
            username=os.getenv('MYSQL_USERNAME'),
            password=os.getenv('MYSQL_PASSWORD'),
            charset=os.getenv('MYSQL_CHARSET', 'utf8mb4')
        )
        db_config_manager.add_config('mysql_default', mysql_config)
    
    # PostgreSQL配置
    if all([os.getenv('POSTGRES_HOST'), os.getenv('POSTGRES_DATABASE'), 
            os.getenv('POSTGRES_USERNAME'), os.getenv('POSTGRES_PASSWORD')]):
        pg_config = DatabaseConfig(
            db_type=DatabaseType.POSTGRESQL,
            host=os.getenv('POSTGRES_HOST'),
            port=int(os.getenv('POSTGRES_PORT', 5432)),
            database=os.getenv('POSTGRES_DATABASE'),
            username=os.getenv('POSTGRES_USERNAME'),
            password=os.getenv('POSTGRES_PASSWORD')
        )
        db_config_manager.add_config('postgres_default', pg_config)